package it.polimi.TravelDream.ejb.searchManager;

import it.polimi.TravelDream.ejb.dtos.RoomDTO;
import it.polimi.TravelDream.ejb.entities.Group;
import it.polimi.TravelDream.ejb.entities.Room;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class RoomManager
 */
@Stateless
public class RoomManager implements RoomMgr {

	@PersistenceContext
    private EntityManager em;
	private String city;
	private List<Room> roomList = new ArrayList<Room>();
	private List<String> hotelName = new ArrayList<String>();
    /**
     * Default constructor. 
     */
    public RoomManager() {
        // TODO Auto-generated constructor stub
    }
    
    
    @Override
    @RolesAllowed({Group._ADMIN})
    public void search(){
    	this.roomList = em.createNamedQuery(Room.FIND_ROOM_BY_CITY, Room.class).setParameter("city", this.city).getResultList();
    	distinctHotelName();
    }
    
    @Override
    @RolesAllowed({Group._ADMIN})
    public void searchAll(){
    	this.roomList = em.createNamedQuery(Room.FIND_ROOM_BY_CITY, Room.class).setParameter("city", this.city).getResultList();
    	distinctHotelName();
    }
    
    @Override
    @RolesAllowed({Group._ADMIN})
    public List <RoomDTO> getRoomResultList(){
	   List <RoomDTO> roomDTOs = new ArrayList <RoomDTO>();
   	
	   for(int i=0; i<this.roomList.size(); i++){
		   RoomDTO roomDTO = convertToDTO (this.roomList.get(i));
		   roomDTOs.add(roomDTO);
	   }
	   
	   return roomDTOs;
    } 
    
    @Override
    @RolesAllowed({Group._ADMIN})
    public String getCity() {
		return city;
	}
    
    @Override
    @RolesAllowed({Group._ADMIN})
	public void setCity(String city) {
		this.city = city;
	}

    @Override
    @RolesAllowed({Group._ADMIN})
	public List<String> getHotelName() {
		return hotelName;
	}

    @Override
    @RolesAllowed({Group._ADMIN})
	public void setHotelName(List<String> hotelName) {
		this.hotelName = hotelName;
	}

	private RoomDTO convertToDTO(Room room){
    	RoomDTO roomDTO = new RoomDTO();
    	roomDTO.setRoomNumber(room.getRoomNumber());
    	roomDTO.setBeds(room.getBeds());
    	roomDTO.setPrice(room.getPrice());
    	roomDTO.setHotelName(room.getHotelName().getName());
    	return roomDTO;
    }
//popola la lista dei nomi degli alberghi	
	private void distinctHotelName(){
		for(Room r:this.roomList){
			if(!this.hotelName.contains(r.getHotelName().getName())){
				this.hotelName.add(r.getHotelName().getName());
			}
				
		}
	}
}
